package controllers;

import play.*;
import play.mvc.*;
import play.data.validation.*;

import java.util.*;

import models.*;

public class Registration extends Controller {

	public static void createNewCustomer(@Required @Valid Person person, @Required @Valid Address address, @Required String password, @Required String passwordValidate)
	{
		validation.equals(password, passwordValidate).message("Passwords don't match!");
		
		//@ TODO This does NOT net work :/ 
		// Person validation may fail if email is already known due to friend invitation (NOT registration) - check for this case
		// and update the values if so
		if( validation.hasError("person.email") && validation.email(person.email).ok ) {
		
			// Check if there's already a customer with that e-mail address -  if true, registration cannot be completed
			Customer exCust = Customer.find("SELECT c FROM Customer c WHERE c.person.email = ?", person.email).first();
			if(exCust != null )
			{
				render("@register", person, address, password, passwordValidate);
			}
			
			// Otherwise use existing person for customer mapping
			// Make email appear valid ;)
			if( validation.errorsMap().containsKey("person.email") )
			{
				validation.errorsMap().keySet().remove("person.email");
			}
			
			// Try to get old person entry
			Person exPerson = Person.find("byEmail", person.email).first();
			exPerson.firstName = person.firstName;
			exPerson.lastName = person.lastName;
			person = exPerson;		
			
			if( validation.errorsMap().keySet().isEmpty() ) {
				// Store person (may be new or modified) and address
				person.save();
				address.save();

				Customer cust = new Customer(password, person, address);
				cust.save();

				session.put("username", person.email);
				success(cust);			
			}
		}
		
		
		if( validation.hasErrors()  ) {
			render("@register", person, address, password, passwordValidate, validation);
		}
		
		// Store person (may be new or modified) and address
		person.save();
		address.save();

		Customer cust = new Customer(password, person, address);
		cust.save();

		session.put("username", person.email);
		success(cust);
	}
	
	public static void register() {
		render();
	}  
	
	public static void success(Customer customer)
	{
		render(customer);
	}
	
}
